from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response

from RBAC.models import Staff

# Create your views here.
from Webmaster import settings
from menus.models import Salary, Car, Files, LoginLog, OperationLog
from utils.EmialTools import SendEmail
from utils.QiNiuTools import QiniuTool


class SalaryView(APIView):
    # 查看所有工资信息
    def get(self, request):
        try:
            uid = request.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        try:
            data = Salary.objects.all()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '获取所有工资信息失败'})
        _list = []
        for i in data:
            _list.append({
                'id': i.id,
                'staff': i.staff.name,
                'atten_days': i.attendance_days,
                'absent_days': i.absent_days,
                'leave_days': i.leave_days,
                'base_salary': i.base_salary,
                'job_salary': i.job_salary,
            })
        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': _list
        })

    # 添加工资条
    def post(self, request):
        try:
            uid = request.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        staff = request.data.get('staff')
        atten_days = request.data.get('atten_days', 0)
        absent_days = request.data.get('absent_days', 0)
        leave_days = request.data.get('leave_days', 0)
        base_salary = request.data.get('base_salary')
        job_salary = request.data.get('job_salary')
        if not all([staff, base_salary, job_salary]):
            return Response({'code': 400, 'msg': '参数错误'})
        if not Staff.objects.filter(id=staff):
            return Response({'code': 400, 'msg': '员工不存在'})
        try:
            Salary.objects.create(
                staff_id=staff,
                attendance_days=atten_days,
                absent_days=absent_days,
                leave_days=leave_days,
                base_salary=base_salary,
                job_salary=job_salary
            )
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '工资条录入失败'})
        return Response({'code': 201, 'msg': '工资条录入成功'})


class SalaryInfo(APIView):
    # 获取单个工资条
    def get(self, request, id):
        try:
            uid = request.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        try:
            data = Salary.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '工资信息不存在'})
        return Response({
            'code': 200,
            'msg': '获取工资条详情成功',
            'data': {
                'id': data.id,
                'staff': data.staff_id,
                'attend_days': data.attendance_days,
                'absent_days': data.absent_days,
                'leave_days': data.leave_days,
                'base_salary': data.base_salary,
                'job_salary': data.job_salary,
            }
        })

    # 修改工资条信息
    def put(self, request, id):
        try:
            uid = request.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        staff = request.data.get('staff')
        atten_days = request.data.get('atten_days', 0)
        absent_days = request.data.get('absent_days', 0)
        leave_days = request.data.get('leave_days', 0)
        base_salary = request.data.get('base_salary')
        job_salary = request.data.get('job_salary')
        if not all([staff, base_salary, job_salary]):
            return Response({'code': 400, 'msg': '参数错误'})
        if not Staff.objects.filter(id=staff):
            return Response({'code': 400, 'msg': '员工不存在'})
        if not Salary.objects.filter(id=id):
            return Response({'code': 400, 'msg': '工资信息不存在'})
        try:
            Salary.objects.filter(id=id).update(
                staff_id=staff,
                attendance_days=atten_days,
                absent_days=absent_days,
                leave_days=leave_days,
                base_salary=base_salary,
                job_salary=job_salary
            )
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '工资条修改失败'})
        return Response({'code': 201, 'msg': '工资条修改成功'})

    # 删除工资条信息
    def delete(self, request, id):
        try:
            uid = request.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        if not Salary.objects.filter(id=id):
            return Response({'code': 400, 'msg': '工资信息不存在'})
        try:
            Salary.objects.filter(id=id).delete()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '工资条删除失败'})
        return Response({'code': 204, 'msg': '工资条删除成功'})


class CarView(APIView):
    # 获取所有车辆信息
    def get(self, request):
        try:
            uid = request.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        try:
            data = Car.objects.all()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '获取所有车辆信息失败'})
        _list = []
        for i in data:
            _list.append({
                'id': i.id,
                'type': i.type,
                'car_id': i.car_id,
                'status': '已调出' if i.status else '空闲',
            })
        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': _list
        })

    # 添加车辆信息
    def post(self, request):
        try:
            uid = request.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        type = request.data.get('type')
        car_id = request.data.get('car_id')
        status = request.data.get('status', False)
        if not all([type, car_id]):
            return Response({'code': 400, 'msg': '参数错误'})
        try:
            Car.objects.create(
                type=type,
                car_id=car_id,
                status=status,
            )
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '车辆信息添加失败'})
        return Response({'code': 201, 'msg': '车辆信息添加成功'})


class CarInfo(APIView):
    # 获取车辆详情
    def get(self, request, id):
        try:
            uid = request.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        try:
            data = Car.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '车辆信息不存在'})
        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': {
                'id': data.id,
                'type': data.type,
                'car_id': data.car_id,
                'status': data.status
            }
        })

    # 修改车辆信息
    def put(self, request, id):
        try:
            uid = request.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        type = request.data.get('type')
        car_id = request.data.get('car_id')
        status = request.data.get('status', False)
        if status:
            status = True
        if not all([type, car_id]):
            return Response({'code': 400, 'msg': '参数错误'})
        if not Car.objects.filter(id=id):
            return Response({'code': 400, 'msg': '车辆信息不存在'})
        try:
            Car.objects.filter(id=id).update(
                type=type,
                car_id=car_id,
                status=status,
            )
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '车辆信息修改失败'})
        return Response({'code': 201, 'msg': '车辆信息修改成功'})

    # 删除车辆信息
    def delete(self, reqeust, id):
        try:
            uid = reqeust.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        if not Car.objects.filter(id=id):
            return Response({'code': 400, 'msg': '车辆信息不存在'})
        try:
            Car.objects.filter(id=id).delete()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '车辆信息删除失败'})
        return Response({'code': 204, 'msg': '车辆信息删除成功'})


class FilesView(APIView):
    # 获取所有材料信息
    def get(self, request):
        try:
            uid = request.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        try:
            data = Files.objects.all()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '获取所有材料信息失败'})
        _list = []
        for i in data:
            _list.append({
                'id': i.id,
                'staff': i.staff.name,
                'file_title': i.file_title,
                'file_url': i.file_url,
            })
        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': _list
        })

    # 上传材料信息
    def post(self, request):
        try:
            uid = request.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        file_title = request.data.get('file_title')
        file_url = request.data.get('url')
        print(file_url, file_title)
        if not all([file_url, file_title]):
            return Response({'code': 400, 'msg': '参数错误'})
        try:
            Files.objects.create(
                staff_id=uid,
                file_title=file_title,
                file_url=file_url
            )
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '材料上传失败'})
        return Response({'code': 201, 'msg': '材料上传成功'})


class FilesInfo(APIView):
    # 获取材料信息
    def get(self, request, id):
        try:
            uid = request.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        try:
            data = Files.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '材料信息不存在'})

        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': {
                'id': data.id,
                'staff': data.staff.name,
                'file_title': data.file_title,
                'url': data.file_url,
            }
        })

    # 删除材料信息
    def delete(self, reqeust, id):
        try:
            uid = reqeust.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        if not Files.objects.filter(id=id):
            return Response({'code': 400, 'msg': '材料信息不存在'})
        try:
            Files.objects.filter(id=id).delete()
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '材料删除失败'})
        return Response({'code': 204, 'msg': '材料删除成功'})


class Upload(APIView):
    def post(self, request):
        try:
            id = request.user_info.get('id')
            # 1.判断用户是否登录
            user = Staff.objects.get(id=id)
        except Exception as e:
            print(e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        #  FILES;获取前端图片
        files = request.FILES.get('file')
        print('>>>>>>>>>>>>', files)
        print('>>>>>>>>>>>>', files.name, files.file)
        # 图片写入位置
        file_dir = settings.STATICFILES_DIRS[0]

        print("图片路径前缀》》》", file_dir)
        # 拼接图片路径
        file_name = file_dir + '/' + files.name
        print('完整图片路径》》》', file_name)
        # 写入指定文件
        with open(file_name, 'wb') as f:
            # 读取图片字节流写入文件
            f.write(files.file.read())
        rsp = QiniuTool().upload(files.name)
        if rsp:
            url = 'http://rq3iaf2vo.bkt.clouddn.com/' + rsp

            return Response({
                'code': 200,
                'msg': '上传成功',
                'files_path': url,
                'files_name': rsp
            })

class LoginLogView(APIView):
    # 获取所有材料信息
    def get(self, request):
        try:
            uid = request.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        try:
            data = LoginLog.objects.all()[::-1]
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '获取日志信息失败'})
        _list = []
        for i in data:
            _list.append({
                'id': i.id,
                'staff': i.staff.name,
                'login_ip': i.login_ip,
                'equipment': i.equipment,
                'time': str(i.login_time),
            })
        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': _list
        })

class Log(APIView):
    # 获取所有材料信息
    def get(self, request):
        try:
            uid = request.user_info.get('id')
            user = Staff.objects.get(id=uid)
        except Exception as e:
            print('>>>>>', e)
            return Response({'msg': '用户不存在或未登录', 'code': '403'})
        try:
            data = OperationLog.objects.all()[::-1]
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '获取日志信息失败'})
        _list = []
        for i in data:
            _list.append({
                'id': i.id,
                'staff': i.staff.name,
                'content': i.content,
                'time':str(i.create_time),
            })
        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': _list
        })

class SendMail(APIView):
    # 发送邮件
    def post(self,request):
        user=request.data.get('user')
        title=request.data.get('title')
        content=request.data.get('context')
        if not all([user,title,content]):
            return Response({'code':400,'msg':'参数错误'})
        SendEmail().send_mail(user,title,content)
        return Response({
            'code':200,
            'msg':'发送成功'
        })
